<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>田地管理 - 禾行通</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <style>
        body {
            background-color: #f8f9fa;
        }
        .map-container {
            height: 70vh;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .field-info {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
        }
        .tool-panel {
            background: white;
            border-radius: 15px;
            padding: 1rem;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .btn-tool {
            margin: 0.2rem;
            border-radius: 10px;
        }
        .field-card {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 0.5rem;
            border-left: 4px solid #28a745;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .field-card:hover {
            transform: translateX(5px);
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }
        .field-card.active {
            border-left-color: #007bff;
            background-color: #f8f9ff;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: linear-gradient(45deg, #28a745, #20c997);">
        <div class="container">
            <a class="navbar-brand" href="/dashboard">
                <i class="fas fa-seedling me-2"></i>禾行通
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="/dashboard">首页</a>
                <a class="nav-link" href="/vehicles">设备管理</a>
                <a class="nav-link active" href="/fields">田地管理</a>
                <a class="nav-link" href="/tasks">任务管理</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <!-- 左侧工具面板 -->
            <div class="col-md-3">
                <div class="tool-panel">
                    <h5><i class="fas fa-tools me-2"></i>地图工具</h5>
                    <div class="d-grid gap-2">
                        <button class="btn btn-outline-primary btn-tool" id="drawPolygon">
                            <i class="fas fa-draw-polygon me-2"></i>绘制地块
                        </button>
                        <button class="btn btn-outline-success btn-tool" id="measureArea">
                            <i class="fas fa-ruler-combined me-2"></i>测量面积
                        </button>
                        <button class="btn btn-outline-warning btn-tool" id="addMarker">
                            <i class="fas fa-map-marker-alt me-2"></i>添加标记
                        </button>
                        <button class="btn btn-outline-danger btn-tool" id="clearAll">
                            <i class="fas fa-trash me-2"></i>清除图层
                        </button>
                    </div>
                </div>

                <!-- 田地列表 -->
                <div class="field-info mt-3">
                    <h5><i class="fas fa-list me-2"></i>田地列表</h5>
                    <div id="fieldList">
                        <div class="field-card" data-field-id="1">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">东区水稻田</h6>
                                    <small class="text-muted">面积: 15.6亩</small>
                                </div>
                                <span class="badge bg-success">已播种</span>
                            </div>
                        </div>
                        <div class="field-card" data-field-id="2">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">西区玉米田</h6>
                                    <small class="text-muted">面积: 22.3亩</small>
                                </div>
                                <span class="badge bg-warning">待耕作</span>
                            </div>
                        </div>
                        <div class="field-card" data-field-id="3">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">南区蔬菜田</h6>
                                    <small class="text-muted">面积: 8.9亩</small>
                                </div>
                                <span class="badge bg-info">生长期</span>
                            </div>
                        </div>
                    </div>
                    <button class="btn btn-primary w-100 mt-2" data-bs-toggle="modal" data-bs-target="#addFieldModal">
                        <i class="fas fa-plus me-2"></i>添加田地
                    </button>
                </div>
            </div>

            <!-- 右侧地图区域 -->
            <div class="col-md-9">
                <div class="field-info">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4><i class="fas fa-map me-2"></i>田地地图</h4>
                        <div class="btn-group">
                            <button class="btn btn-outline-secondary" id="satelliteView">
                                <i class="fas fa-satellite me-1"></i>卫星
                            </button>
                            <button class="btn btn-outline-secondary active" id="mapView">
                                <i class="fas fa-map me-1"></i>地图
                            </button>
                        </div>
                    </div>
                    <div id="map" class="map-container"></div>
                </div>

                <!-- 选中田地信息 -->
                <div class="field-info mt-3" id="selectedFieldInfo" style="display: none;">
                    <h5><i class="fas fa-info-circle me-2"></i>田地详情</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>名称:</strong> <span id="fieldName">-</span></p>
                            <p><strong>面积:</strong> <span id="fieldArea">-</span></p>
                            <p><strong>作物类型:</strong> <span id="cropType">-</span></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>种植日期:</strong> <span id="plantDate">-</span></p>
                            <p><strong>预计收获:</strong> <span id="harvestDate">-</span></p>
                            <p><strong>状态:</strong> <span id="fieldStatus">-</span></p>
                        </div>
                    </div>
                    <div class="btn-group">
                        <button class="btn btn-primary btn-sm">
                            <i class="fas fa-edit me-1"></i>编辑
                        </button>
                        <button class="btn btn-success btn-sm">
                            <i class="fas fa-tasks me-1"></i>创建任务
                        </button>
                        <button class="btn btn-info btn-sm">
                            <i class="fas fa-chart-line me-1"></i>查看数据
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加田地模态框 -->
    <div class="modal fade" id="addFieldModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加新田地</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addFieldForm">
                        <div class="mb-3">
                            <label class="form-label">田地名称</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">作物类型</label>
                            <select class="form-select" name="cropType" required>
                                <option value="">请选择作物类型</option>
                                <option value="水稻">水稻</option>
                                <option value="玉米">玉米</option>
                                <option value="小麦">小麦</option>
                                <option value="蔬菜">蔬菜</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">种植日期</label>
                            <input type="date" class="form-control" name="plantDate">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" name="notes" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveField">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script>
        // 初始化地图
        const map = L.map('map').setView([39.9042, 116.4074], 13);
        
        // 添加地图图层
        const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        
        const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: 'Tiles © Esri'
        });
        
        // 绘制工具
        let drawingMode = null;
        let drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);
        
        // 示例田地数据
        const fieldsData = {
            1: {
                name: '东区水稻田',
                area: '15.6亩',
                cropType: '水稻',
                plantDate: '2024-03-15',
                harvestDate: '2024-09-15',
                status: '已播种',
                coordinates: [[39.910, 116.400], [39.915, 116.400], [39.915, 116.410], [39.910, 116.410]]
            },
            2: {
                name: '西区玉米田',
                area: '22.3亩',
                cropType: '玉米',
                plantDate: '2024-04-01',
                harvestDate: '2024-10-01',
                status: '待耕作',
                coordinates: [[39.900, 116.390], [39.908, 116.390], [39.908, 116.405], [39.900, 116.405]]
            },
            3: {
                name: '南区蔬菜田',
                area: '8.9亩',
                cropType: '蔬菜',
                plantDate: '2024-02-20',
                harvestDate: '2024-06-20',
                status: '生长期',
                coordinates: [[39.895, 116.400], [39.900, 116.400], [39.900, 116.408], [39.895, 116.408]]
            }
        };
        
        // 添加田地到地图
        Object.keys(fieldsData).forEach(fieldId => {
            const field = fieldsData[fieldId];
            const polygon = L.polygon(field.coordinates, {
                color: getStatusColor(field.status),
                fillOpacity: 0.3
            }).addTo(map);
            
            polygon.bindPopup(`
                <strong>${field.name}</strong><br>
                面积: ${field.area}<br>
                作物: ${field.cropType}<br>
                状态: ${field.status}
            `);
            
            polygon.on('click', () => selectField(fieldId));
        });
        
        function getStatusColor(status) {
            switch(status) {
                case '已播种': return '#28a745';
                case '待耕作': return '#ffc107';
                case '生长期': return '#17a2b8';
                default: return '#6c757d';
            }
        }
        
        function selectField(fieldId) {
            // 清除之前的选中状态
            document.querySelectorAll('.field-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // 设置当前选中
            document.querySelector(`[data-field-id="${fieldId}"]`).classList.add('active');
            
            // 显示田地详情
            const field = fieldsData[fieldId];
            document.getElementById('fieldName').textContent = field.name;
            document.getElementById('fieldArea').textContent = field.area;
            document.getElementById('cropType').textContent = field.cropType;
            document.getElementById('plantDate').textContent = field.plantDate;
            document.getElementById('harvestDate').textContent = field.harvestDate;
            document.getElementById('fieldStatus').textContent = field.status;
            document.getElementById('selectedFieldInfo').style.display = 'block';
        }
        
        // 田地卡片点击事件
        document.querySelectorAll('.field-card').forEach(card => {
            card.addEventListener('click', () => {
                const fieldId = card.dataset.fieldId;
                selectField(fieldId);
                
                // 地图定位到该田地
                const field = fieldsData[fieldId];
                const bounds = L.latLngBounds(field.coordinates);
                map.fitBounds(bounds);
            });
        });
        
        // 地图视图切换
        document.getElementById('satelliteView').addEventListener('click', function() {
            map.removeLayer(osmLayer);
            map.addLayer(satelliteLayer);
            this.classList.add('active');
            document.getElementById('mapView').classList.remove('active');
        });
        
        document.getElementById('mapView').addEventListener('click', function() {
            map.removeLayer(satelliteLayer);
            map.addLayer(osmLayer);
            this.classList.add('active');
            document.getElementById('satelliteView').classList.remove('active');
        });
        
        // 绘制工具事件
        document.getElementById('drawPolygon').addEventListener('click', function() {
            drawingMode = 'polygon';
            map.getContainer().style.cursor = 'crosshair';
            this.classList.add('active');
        });
        
        document.getElementById('measureArea').addEventListener('click', function() {
            drawingMode = 'measure';
            map.getContainer().style.cursor = 'crosshair';
            this.classList.add('active');
        });
        
        document.getElementById('addMarker').addEventListener('click', function() {
            drawingMode = 'marker';
            map.getContainer().style.cursor = 'crosshair';
            this.classList.add('active');
        });
        
        document.getElementById('clearAll').addEventListener('click', function() {
            drawnItems.clearLayers();
            drawingMode = null;
            map.getContainer().style.cursor = '';
            document.querySelectorAll('.btn-tool').forEach(btn => btn.classList.remove('active'));
        });
        
        // 地图点击事件
        let drawingPoints = [];
        map.on('click', function(e) {
            if (drawingMode === 'marker') {
                L.marker(e.latlng).addTo(drawnItems)
                    .bindPopup('新标记点')
                    .openPopup();
                drawingMode = null;
                map.getContainer().style.cursor = '';
                document.querySelectorAll('.btn-tool').forEach(btn => btn.classList.remove('active'));
            } else if (drawingMode === 'polygon' || drawingMode === 'measure') {
                drawingPoints.push(e.latlng);
                
                if (drawingPoints.length >= 3) {
                    const polygon = L.polygon(drawingPoints).addTo(drawnItems);
                    
                    if (drawingMode === 'measure') {
                        const area = L.GeometryUtil.geodesicArea(polygon.getLatLngs()[0]);
                        const areaInMu = (area / 666.67).toFixed(2); // 转换为亩
                        polygon.bindPopup(`面积: ${areaInMu} 亩`).openPopup();
                    }
                    
                    drawingPoints = [];
                    drawingMode = null;
                    map.getContainer().style.cursor = '';
                    document.querySelectorAll('.btn-tool').forEach(btn => btn.classList.remove('active'));
                }
            }
        });
        
        // 保存田地
        document.getElementById('saveField').addEventListener('click', function() {
            const form = document.getElementById('addFieldForm');
            const formData = new FormData(form);
            
            // 这里应该发送到后端保存
            console.log('保存田地:', Object.fromEntries(formData));
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addFieldModal'));
            modal.hide();
            
            // 重置表单
            form.reset();
            
            // 显示成功消息
            alert('田地添加成功！');
        });
    </script>
</body>
</html>